package com.huxin.servelt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huxin.pojo.BookTypeInfo;
import com.huxin.pojo.ConditionalQueryDTO;
import com.huxin.pojo.PageBean;
import com.huxin.pojo.UserInfo;
import com.huxin.service.Userservice;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 读者条件查询
 */
@WebServlet("/readerConditionalQuery")
public class ReaderConditionalQueryServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Userservice userservice = new Userservice();
//        List<UserInfo> userInfos = new ArrayList<UserInfo>();
        //接收搜索类型以及输入框的内容 并封装为对象
        String s = request.getReader().readLine();
        ConditionalQueryDTO conditionalQueryDTO = JSON.parseObject(s, ConditionalQueryDTO.class);
        int page=1;//开始页
        int size=10;//每页显示十条数据
        if(null!=(request.getParameter("page"))){
            page= Integer.parseInt(request.getParameter("page"));
        }
        if(null!=(request.getParameter("size"))){
            size=Integer.parseInt(request.getParameter("size"));
        }

        PageBean<UserInfo> userInfoPageBean = null;
        if ("username".equals(conditionalQueryDTO.getType())){//按照登录账号查询用户
            userInfoPageBean =userservice.selectUserByUsername(conditionalQueryDTO.getText(),page,size);
        } else if ("name".equals(conditionalQueryDTO.getType())) {//按照用户名查询用户
            userInfoPageBean=userservice.selectUserByname(conditionalQueryDTO.getText(),page,size);
        }else {//查询所有
            userInfoPageBean=userservice.selectallreader(page,size);
        }
        String jsonString = JSONObject.toJSONString(userInfoPageBean);
        response.getWriter().write(jsonString);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
